using Godot;
using System;

public partial class Player : CharacterBody2D
{
    private AnimatedSprite2D AnimatedSprite2DNode;
    private const float Speed = 130.0f;
    private const float JumpVelocity = -300.0f;

    private float _gravity = ProjectSettings.GetSetting("physics/2d/default_gravity").AsSingle();


    public override void _Ready()
    {
        AnimatedSprite2DNode = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
    }

    public override void _PhysicsProcess(double delta)
    {
        if (!IsOnFloor())
            Velocity = new(Velocity.X, Velocity.Y + _gravity * (float)delta);
        
        if(Input.IsActionJustPressed("Jump") && IsOnFloor())
            Velocity = new(Velocity.X, JumpVelocity);


        var direction = Input.GetAxis("MoveLeft", "MoveRight");

        if (direction > 0)
        {
            AnimatedSprite2DNode.FlipH = false;
        }
        else if (direction < 0)
        {
            AnimatedSprite2DNode.FlipH = true;
        }


        if (IsOnFloor())
        {
            if (direction == 0)
            {
                AnimatedSprite2DNode.Play("Idle");
            }
            else
            {
                AnimatedSprite2DNode.Play("Run");
            }
        }
        else
        {
            AnimatedSprite2DNode.Play("Jump");
        }
        

        
        
        if (!Mathf.IsZeroApprox(direction))
            Velocity = new(direction * Speed , Velocity.Y);
        else
        {
            Velocity = new(Mathf.MoveToward(Velocity.X,0,Speed), Velocity.Y);
        }

        MoveAndSlide();

    }
}
